package com.xw.controller.xw;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xw.controller.base.BaseController;
import com.xw.entity.Page;
import com.xw.entity.system.User;
import com.xw.service.xw.caseOrder.CaseOrderService;
import com.xw.service.xw.cfOrder.CfOrderService;
import com.xw.service.xw.patient.PatientService;
import com.xw.util.AppUtil;
import com.xw.util.Const;
import com.xw.util.DateUtil;
import com.xw.util.PageData;
/**
 * 类名称: CfCardController
 * 类描述: 处方单controller
 * @author : gce
 * @date   : 2017-12-1
 */
@Controller
@RequestMapping( value = "/cfOrder")
public class CfOrderController extends BaseController {
	
	@Resource(name="cfOrderService")
	private CfOrderService cfOrderService;
	@Resource(name="patientService")
	private PatientService patientService;
	@Resource(name="caseOrderService")
	private CaseOrderService caseOrderService;
	
	/**
	 * 查询处方单列表 ，根据患者id
	 * @param page
	 * @throws Exception
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-5
	 */
	@RequestMapping( value = "/listByPid")
	public ModelAndView listByPid(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		page.setPd(pd);
		List<PageData> cfOrderList  = cfOrderService.listByPid(page);
		mv.addObject("cfOrderList", cfOrderList);
		mv.addObject("pd", pd);
		mv.setViewName("xw/cfOrder/cfOrderList");
		return mv ;
	}
	
	/**
	 * 查询处方单列表 ，根据处方单id
	 * @param page
	 * @throws Exception
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-15
	 */
	@RequestMapping( value = "/listByCid")
	public ModelAndView listByCid(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		page.setPd(pd);
		List<PageData> cfOrderList  = cfOrderService.listByCid(page);
		mv.addObject("cfOrderList", cfOrderList);
		mv.setViewName("xw/cfOrder/cfOrderList");
		return mv ;
	}
	
	/**
	 * 新建处方单之前，查询匹配条件的所有患者的最后一次病历
	 * @param page
	 * @throws Exception
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-5
	 */
	@RequestMapping( value = "/findCaseOrder")
	public ModelAndView findCaseOrder(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		if(pd.get("id")==null || pd.get("id").equals("")){
			page.setPd(pd);
			//根据条件（姓名或电话），查询匹配患者的最后一次病历单详情
			List<PageData> caseOrderList  = cfOrderService.findCase(page);
			if(caseOrderList.size()==0){		//没有数据
				mv.addObject("has", 0);
				mv.setViewName("xw/cfOrder/choosePatient");
			}else if(caseOrderList.size()==1){	//只要一条数据
				mv.addObject("has", 1);
				int age = DateUtil.getAge((Date)caseOrderList.get(0).get("birth"));
				caseOrderList.get(0).put("age", age);
				mv.addObject("caseOrder", caseOrderList.get(0));
				mv.setViewName("xw/cfOrder/addCfOrder");
			}else{								//多条数据
				mv.addObject("has", 2);
				for (PageData pageData : caseOrderList) {
					int age = DateUtil.getAge((Date)pageData.get("birth"));
					pageData.put("age", age);
				}
				mv.addObject("caseOrderList", caseOrderList);
				mv.setViewName("xw/cfOrder/choosePatient");
			}
		}else{
			PageData pd2 = caseOrderService.findById(pd);
			mv.addObject("has", 1);
			int age = DateUtil.getAge((Date)pd2.get("birth"));
			pd2.put("age", age);
			mv.addObject("caseOrder", pd2);
			mv.setViewName("xw/cfOrder/addCfOrder");
		}
		mv.addObject("pd", pd);
		return mv ;
	}
	
	/**
	 * 跳转到添加处方单前的搜索患者页面
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-5
	 */
	@RequestMapping(value = "/goAddCfOrder")
	public ModelAndView goAddCfOrder(){
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("xw/cfOrder/choosePatient");
		return mv;
	}
	
	/**
	 * 跳转到选择药品页面
	 * @return: ModelAndView
	 * @author: gce
	 * @throws Exception 
	 * @date  : 2017-12-5
	 */
	@RequestMapping(value = "/chooseYp")
	public ModelAndView chooseYp(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		//查询所有药品
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = new User();
		user = (User)session.getAttribute(Const.SESSION_USER);
		pd.put("mzId", user.getMzid());
		
		page.setPd(pd);
		List<PageData> ypList = cfOrderService.yplistPage(page);
		mv.addObject("ypList", ypList);
		mv.addObject("pd", pd);
		mv.setViewName("xw/cfOrder/chooseYp");
		return mv;
	}
	
	/**
	 * 添加处方单
	 * @return: Object
	 * @author: gce
	 * @throws Exception 
	 * @date  : 2017-12-12
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save() throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		String msg = "success";
		PageData pd = new PageData();
		pd = this.getPageData();				//页面传过来的数据
		
		//添加处方单
		PageData pd2 = new PageData();						//要添加处方单的数据
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = new User();
		user = (User)session.getAttribute(Const.SESSION_USER);
		
		pd2.put("hzId", pd.get("hzId"));		//患者Id
		
		PageData pd3 = patientService.findById(pd2);	//患者信息
		
		pd2.put("cfdCode", "");					//处方单编码
		pd2.put("caseId", pd.get("caseId"));	//病历单ID
		pd2.put("ysId", user.getUSER_ID());		//患者Id
		pd2.put("tell", pd.get("yiZhu"));		//医嘱
		pd2.put("shr", null==pd3.get("shr")?"":pd3.get("shr"));			//收货人
		pd2.put("shrPhone", null==pd3.get("shrphone")?"":pd3.get("shrphone"));			//收货人电话
		pd2.put("shrAddress",null== pd3.get("shraddress")?"":pd3.get("shraddress"));		//收货人地址
		pd2.put("ypPrice", pd.get("ypje"));		//药品金额
		pd2.put("zlPrice", pd.get("zlfy"));		//治疗费用
		pd2.put("totalPrice", pd.get("hjje"));	//合计金额
		pd2.put("createDate", new Date());
		pd2.put("state", 0);
		pd2.put("mzId", user.getMzid());
		
		long id = cfOrderService.save(pd2);
		
		String ypString = (String) pd.get("ypList") ;
		
		//[["100","10","1000.00","55"],["100","10","1000.00","55"]]
		//[["100","10","1000.00","55"]]
		//[]
		if(ypString.startsWith("[[")){	
			ypString = ypString.substring(2, ypString.length()-2);
			if(ypString.indexOf("],[")!=-1){	//包含
				String[] yp = ypString.split("],\\[");
				for (String string : yp) {				//循环添加已开处方药品的数据
					String[] ypAttr = string.split(",");	//单价、用量、总价、药品id
					PageData pd4 = new PageData();		
					
					Object ypId = (Object)ypAttr[3].replace("\"", "");
					Object price = (Object)ypAttr[0].replace("\"", "");
					Object number = (Object)ypAttr[1].replace("\"", "");
					Object totalPrice = (Object)ypAttr[2].replace("\"", "");
					
					pd4.put("cfdId",id );	//处方单ID
					pd4.put("ypId", ypId);			//药品id
					pd4.put("price",  price);		//药品单价
					pd4.put("number", number);		//药品用量
					pd4.put("totalPrice", totalPrice);		//药品总价
					pd4.put("ysId", user.getUSER_ID());		//医师ID
					pd4.put("createDate",new Date() );		//创建时间
					pd4.put("updateDate",new Date() );		//修改时间
					
					cfOrderService.saveYkcfyp(pd4);		//添加已开处方药品
					pd4.put("mzId", user.getMzid());
					 //查询库存
					PageData pd5 = cfOrderService.findKc(pd4);
					Double kctotal = Double.parseDouble(pd5.get("kctotal").toString());
					Double num = Double.parseDouble((String)number);
					BigDecimal b1 = new BigDecimal(kctotal);
					BigDecimal b2 = new BigDecimal(num);
					pd5.put("kctotal", b1.subtract(b2));
					//修改库存
					cfOrderService.updateKc(pd5);
				}
			}else if(ypString.indexOf(",")!=-1){
				
				String[] ypAttr = ypString.split(",");
				PageData pd4 = new PageData();	
				Object ypId = (Object)ypAttr[3].substring(1, ypAttr[3].length()-1);
				Object price = (Object)ypAttr[0].substring(1, ypAttr[0].length()-1);
				Object number = (Object)ypAttr[1].substring(1, ypAttr[1].length()-1);
				Object totalPrice = (Object)ypAttr[2].substring(1, ypAttr[2].length()-1);
				pd4.put("cfdId",id );	//处方单ID
				pd4.put("ypId", ypId);			//药品id
				pd4.put("price", price );		//药品单价
				pd4.put("number", number );		//药品用量
				pd4.put("totalPrice", totalPrice );		//药品总价
				pd4.put("ysId", user.getUSER_ID());		//医师ID
				pd4.put("createDate",new Date() );		//创建时间
				pd4.put("updateDate",new Date() );		//修改时间
				
				cfOrderService.saveYkcfyp(pd4);		//添加已开处方药品
				pd4.put("mzId", user.getMzid());
				 //查询库存
				PageData pd5 = cfOrderService.findKc(pd4);
				Double kctotal = Double.parseDouble(pd5.get("kctotal").toString());
				Double num = Double.parseDouble((String)number);
				BigDecimal b1 = new BigDecimal(kctotal);
				BigDecimal b2 = new BigDecimal(num);
				pd5.put("kctotal", b1.subtract(b2));
				//修改库存
				cfOrderService.updateKc(pd5);
			}
		}
		
		map.put("msg", msg);
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 查询处方单详情，根据处方单ID(id)
	 * @return: ModelAndView
	 * @author: gce
	 * @throws Exception 
	 * @date  : 2017-12-7
	 */
	@RequestMapping(value = "/findByCfId")
	public ModelAndView findByCfId() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData pd2 = cfOrderService.findByCfId(pd);
		Page page = this.getPage();
		page.setPd(pd);
		//查询该处方药品列表
		List<PageData> ypList = cfOrderService.ykyplistPage(page);
		
		mv.addObject("pd", pd2);
		mv.addObject("ypList", ypList);
		mv.setViewName("xw/cfOrder/cfDetail");
		return mv;
	}
	
		//删除单个处方
		@RequestMapping(value = "/deleteOne")
		@ResponseBody
		public Object deleteOne(){
			Map<String, String> map = new HashMap<String, String>();
			String msg = "success";
			PageData pd = new PageData();
			try {
				pd = this.getPageData();
				int result;
					result = cfOrderService.delete(pd);
					if(result>0){
					}else{
						msg = "删除失败";
					}
				} catch (Exception e) {
					logger.error(e.toString(), e);
					msg = "--删除异常--";
				}
			map.put("msg", msg);
			return AppUtil.returnObject(new PageData(), map);
		}

}
